package com.jims.api.v1.controller.doctor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jims.master.common.data.Message;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.Encodes;
import com.jims.master.common.utils.SecurityUtil;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.modules.base.medicalService.entity.SDefaultServe;
import com.jims.master.modules.base.medicalService.service.SDefaultServeService;
import com.jims.master.modules.base.order.service.SordersService;
import com.jims.master.modules.base.user.entity.DocInfo;
import com.jims.master.modules.base.user.entity.MasterDoctorinfo;
import com.jims.master.modules.base.user.service.DocInfoService;
import com.jims.master.modules.base.user.service.MasterDoctorinfoService;
import com.jims.master.modules.base.user.service.SysDepartmentService;
import com.jims.master.modules.doctor.medicalService.entity.SDoctorPlan;
import com.jims.master.modules.doctor.medicalService.entity.SDoctorServe;
import com.jims.master.modules.doctor.medicalService.service.SDoctorPlanService;
import com.jims.master.modules.doctor.medicalService.service.SDoctorServeService;
import com.jims.master.modules.sys.utils.netease.UUIDUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by Administrator on 2017/12/7.
 */
@RestController
@RequestMapping(value = "/doctorServer")
public class DoctorServerController {
    @Autowired
    private SDoctorServeService sDoctorServeService;
    @Autowired
    private SordersService sordersService;
    @Autowired
    private SDoctorPlanService sDoctorPlanService;
    @Autowired
    private SysDepartmentService sysDepartmentService;
    @Autowired
    private SDefaultServeService sDefaultServeService;
    @Autowired
    private MasterDoctorinfoService masterDoctorinfoService;
    @Autowired
    private DocInfoService docInfoService;
     /**
       * @Title:
       * @Description: （获取服务列表）
        * @param
       * @return
       * @author jict
       * @date 2017/12/8
       * @throws
      */
    @RequestMapping(value = "V100/doctorServerList",method ={RequestMethod.GET,RequestMethod.POST})
    public String doctorServerList(){
        Message mes = new Message();
        List<SDoctorServe> list = sDoctorServeService.doctorServerList();
        for(int i =0;i<list.size();i++){
            List<SDoctorPlan> sDoctorPlan = list.get(i).getsDoctorPlan();
            for(int j =0;j<sDoctorPlan.size();j++){
                int planNum =sDoctorPlanService.findOrderedNumOfPlan(sDoctorPlan.get(j));
                sDoctorPlan.get(j).setOrderedNum(planNum);
            }
        }
        String count =sordersService.personOrderCount();
        Map<String,Object> mapList = new HashMap<String,Object>();
        mapList.put("sdoctorServeList",list);
        mapList.put("allSignCount",count);
        mes.setData(mapList);
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * @Title:
     * @Description: （获取服务医生列表）
     * @param
     * @return
     * @author jict
     * @date 2017/12/8
     * @throws
     */
    @RequestMapping(value = "V100/doctorList",method ={RequestMethod.GET,RequestMethod.POST})
    public String doctorList(String area,String titles,String name,String hospital,String parts,String type,String pageNo){
        int pageNum = Integer.parseInt(pageNo)*10;
        Message mes = new Message();
        String depNo = sysDepartmentService.getDepNo(parts);
        List<String> list1 = new ArrayList<>();
        if (parts!=null&&parts.equals("其他")) {
            list1.add("03");
            list1.add("04");
            list1.add("05");
            list1.add("07");
        }
        List<SDoctorServe> list = sDoctorServeService.doctorList(area,titles,name,hospital,depNo,list1,type,pageNum,parts);
        for(int i=0;i<list.size();i++){
            MasterDoctorinfo masterDoctorinfo = list.get(i).getMasterDoctorinfo();
            String sinnum = sordersService.buyOrderCount(masterDoctorinfo.getId());
            masterDoctorinfo.setSignFamilCount(sinnum);
        }
        mes.setData(list);
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * @Title:
     * @Description: （获取家庭医生列表）
     * @param
     * @return
     * @author jict
     * @date 2017/12/8
     * @throws
     */
    @RequestMapping(value = "V100/doctorListByArea",method ={RequestMethod.GET,RequestMethod.POST})
    public String doctorListByArea(String hospital,String parts,String type,String area){
        Message mes = new Message();
        String depNo = sysDepartmentService.getDepNo(parts);
        List<String> list1 = new ArrayList<>();
        if (parts!=null&&parts.equals("其他")) {
            list1.add("03");
            list1.add("04");
            list1.add("05");
            list1.add("07");
        }
        List<SDoctorServe> list = sDoctorServeService.doctorListByArea(hospital,depNo,list1,type,area);
        if(list.size()==0){
            String result =area.substring(0,4);
            list=sDoctorServeService.doctorListByArea(hospital,depNo,list1,type,result);
            if (list.size()==0){
                list=sDoctorServeService.doctorListByAll(hospital,depNo,list1,type);
            }
        }
        for(int i=0;i<list.size();i++){
            MasterDoctorinfo masterDoctorinfo = list.get(i).getMasterDoctorinfo();
            String sinnum = sordersService.buyOrderCount(masterDoctorinfo.getId());
            masterDoctorinfo.setSignFamilCount(sinnum);
        }
        mes.setData(list);
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * 查询所有医生
     * @param hospital
     * @param parts
     * @param area
     * @return
     */
    @RequestMapping(value = "V100/AlldoctorList",method ={RequestMethod.GET,RequestMethod.POST})
    public String AlldoctorList(String hospital,String parts,String area){
        Message mes = new Message();
        Map<String,Object> data=new HashMap<String,Object>();
        List<DocInfo> list = null;
        List<DocInfo> listAll = null;
        if(area==null||"".equals(area)){
            list=docInfoService.getDocByArea(hospital,parts,area);
        }else {
        list= docInfoService.getDocByArea(hospital,parts,area);
        if(list.size()==0){
            String result =area.substring(0,4);
            list = docInfoService.getDocByArea(hospital,parts,result);
            if (list.size()==0) {
                list=docInfoService.getAllDoc();
            }else{
                listAll=docInfoService.getDocBys(hospital,parts,result);
            }
        }else{
            listAll=docInfoService.getDocBys(hospital,parts,area);
        }
        }
        data.put("list",list);
        data.put("listAll",listAll);
        return SecurityUtil.encryptMsgData(data);
    }

    /**
     * @Title:
     * @Description: （获取服务详情）
     * @param
     * @return
     * @author jict
     * @date 2017/12/8
     * @throws
     */
    @RequestMapping(value = "V100/getServerById",method ={RequestMethod.GET,RequestMethod.POST})
    public String getServerById(@RequestParam(required=true)String serverId){
        Message mes = new Message();
        SDoctorServe list = sDoctorServeService.getServerById(serverId);
        if (list!=null&&!"".equals(list)) {
            MasterDoctorinfo masterDoctorinfo = list.getMasterDoctorinfo();
            String sinnum = sordersService.buyOrderCount(masterDoctorinfo.getId());
            masterDoctorinfo.setSignFamilCount(sinnum);
            list.setServeContent(Encodes.unescapeHtml(list.getServeContent()));
            List<SDoctorPlan> list1 = list.getsDoctorPlan();
            for(int i =0;i<list1.size();i++){
                SDoctorPlan sDoctorPlan = list1.get(i);
                int planNum =sDoctorPlanService.findOrderedNumOfPlan(sDoctorPlan);
                sDoctorPlan.setOrderedNum(planNum);
            }
            mes.setData(list);
            return SecurityUtil.encryptMsgData(mes);
        }else{
            mes.setData(list);
            return SecurityUtil.encryptMsgData(mes);
        }

    }

    /**
     * @Title:
     * @Description: （获取系统服务）
     * @param
     * @return
     * @author jict
     * @date 2017/12/25
     * @throws
     */
    @RequestMapping(value = "V100/getSDefaultServe",method ={RequestMethod.GET,RequestMethod.POST})
    public String getSDefaultServe() {
        Message mes = new Message();
        List<SDefaultServe> list = sDefaultServeService.getSDefaultServe();
        for(int i=0;i<list.size();i++) {
            //去除html标签
            list.get(i).setServeContent(Encodes.unescapeHtml(list.get(i).getServeContent()));
        }
        mes.setData(list);
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * @Title:
     * @Description: （保存医生发布的服务）
     * @param
     * @return
     * @author jict
     * @date 2017/12/25
     * @throws
     */
    @RequestMapping(value = "V100/saveServer",method ={RequestMethod.GET,RequestMethod.POST})
    public String getServer(@RequestParam(required=true)String defaultId,@RequestParam(required=true)String doctorId,@RequestParam(required=true)String serveType,String serveState) {
        Message mes = new Message();
        SDoctorServe sDoctorServe = new SDoctorServe();
        SDefaultServe list = sDefaultServeService.get(defaultId);
        sDoctorServe.setDefaultId(defaultId);
        sDoctorServe.setDoctorId(doctorId);
        sDoctorServe.setTitle(list.getTitle());
        sDoctorServe.setIntroduce(list.getIntroduce());
        sDoctorServe.setPrice(list.getPrice());
        sDoctorServe.setCost(list.getPrice());
        sDoctorServe.setType(serveType);
        sDoctorServe.setServeContent(list.getServeContent());
        sDoctorServe.setPicUrl(list.getPicUrl());
        sDoctorServe.setServeType("1");
        sDoctorServe.setServeState(serveState);
        int result = sDoctorServeService.save(sDoctorServe);
        if (result ==1 ){
            mes.setData("发布服务成功");
        }else{
            mes.setData("发布服务失败");
        }
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * @Title:
     * @Description: （医生上门设置服务时间）
     * @param
     * @return
     * @author jict
     * @date 2017/12/26
     * @throws
     */
    @RequestMapping(value = "V100/saveServerPlan",method ={RequestMethod.GET,RequestMethod.POST})
    public String saveServerPlan(String sDoctorPlanList) {
        JSONArray jsonArray = JSONArray.parseArray(sDoctorPlanList);
        Message mes = new Message();
        int result = 0;
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonJ = jsonArray.getJSONObject(i);
            String ss = jsonJ.toString();
            SDoctorPlan sDoctorPlan = JSON.parseObject(ss,SDoctorPlan.class);
            int s = sDoctorPlanService.save(sDoctorPlan);
            if (s>0){
                result++;
            }
        }
        if (result>0){
            mes.setData("发布服务日程成功");
        }
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * @Title:
     * @Description: （医生设置服务是否生效）
     * @param serverId 服务id
     * @param state 服务状态
     * @author jict
     * @date 2017/12/26
     * @throws
     */
    @RequestMapping(value = "V100/stopServer",method ={RequestMethod.GET,RequestMethod.POST})
    public String stopServer(@RequestParam(required=true)String serverId,@RequestParam(required=true)String state) {
        Message mes = new Message();
        int result = sDoctorServeService.stopServer(serverId,state);
        if (result == 1 && state.equals("1")) {
            mes.setData("启用服务成功");
            return SecurityUtil.encryptMsgData(mes);
        }else{
            mes.setData("停运服务成功");
            return SecurityUtil.encryptMsgData(mes);
        }
    }

    /**
     * @Title:
     * @Description: （私人医生设置周期）
     * @param serverId 服务id
     * @author jict
     * @date 2017/12/26
     * @throws
     */
    @RequestMapping(value = "V100/setCycle",method ={RequestMethod.GET,RequestMethod.POST})
    public String setCycle(@RequestParam(required=true)String serverId,String cycle,String cost) {
        Message mes = new Message();
        int result = sDoctorServeService.setCycle(serverId,cycle,cost);
        if (result == 1) {
            mes.setData("设置成功");
            return SecurityUtil.encryptMsgData(mes);
        }else{
            mes.setData("设置失败");
            return SecurityUtil.encryptMsgData(mes);
        }
    }

    /**
     * @Title:
     * @Description: （查询医生开通服务列表）
     * @param doctorId 服务id
     * @author jict
     * @date 2017/12/26
     * @throws
     */
    @RequestMapping(value = "V100/serverList",method ={RequestMethod.GET,RequestMethod.POST})
    public String serverList(@RequestParam(required=true)String doctorId) {
        Message mes = new Message();
        List<SDoctorServe> list = sDoctorServeService.serveListByDoctor(doctorId);
        mes.setData(list);
        return SecurityUtil.encryptMsgData(mes);
    }

    /**
     * base64图片上传
     * @param fileStr
     * @return
     */
    @RequestMapping(value = "V100/base64",method ={RequestMethod.GET,RequestMethod.POST})
    public static String str2File(String fileStr,String picType,String userId ,HttpServletRequest request){
        String resylt = fileStr.replaceAll(" ","+");
        StringBuffer sb = new StringBuffer();
        String ss = resylt.replaceAll("data:image/jpeg;base64,","");
        String [] result= ss.split(",");
        String home = request.getSession().getServletContext().getRealPath("");
        Message msa = new Message();
        String datePath = DateUtils.formatDate(new Date(), "yyyy");
        //初始化上传文件路径
        String pathUrl = File.separator + datePath + File.separator + userId + File.separator + picType;
        if (fileStr == null){
            //文件数据为空
            msa.setData("文件数据为空");
            return SecurityUtil.encryptMsgData(msa);
        }
        try {
            //Base64解码
            for(int j =0;j<result.length;j++){
                byte[] b = Base64.decodeBase64(result[j]);
                for(int i=0;i<b.length;++i){
                    if(b[i]<0){//调整异常数据
                        b[i]+=256;
                    }
                }
                //生成文件，并保存在服务器硬盘上
                String str = UUIDUtil.getUUID();
                String url = pathUrl+File.separator +str+".jpg";
                OutputStream out = new FileOutputStream(home + url);
                out.write(b);
                out.flush();
                out.close();
                sb.append(url + ",");
            }
            msa.setData(sb);
            return SecurityUtil.encryptMsgData(msa);
        } catch (Exception e)  {
            e.printStackTrace();
            msa.setData("上传异常");
            return SecurityUtil.encryptMsgData(msa);
        }
    }
}
